<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/4/30
 * Time: 22:47
 */

namespace app\admin\controller;


use app\common\model\AccountLog;
use app\common\model\BusInquiry;
use app\common\model\BusInquiryDetail;
use app\common\model\BusInquiryDetailSupplier;
use app\common\model\BusInquirySuppliers;
use app\common\model\InvoiceLog;
use app\common\model\SalesCompany;
use app\common\model\SendGoodsLog;
use app\common\model\SuppliersCompany;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\response\Json;

class Purchase extends Admin
{
    public $model;
    public function __construct()
    {
        header("Access-Control-Allow-Origin:*");
        header("Access-Control-Allow-Method:POST,GET");
        header("Access-Control-Allow-Headers:Authorization, X-Requested-With, Cache-Control, Expires, Content-Type");
        $this->model = new BusInquirySuppliers();
    }
    /**
     * 获取公司列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getList(){
        $page = input('page', 1);
        $limit = input('limit', 20);
        $due_date = input('due_date','');
        $role_id = input('opt_role_id','','trim');

        $param = $this->getParam();
        if($due_date){
            $date_arr = explode(' - ',$due_date);
            if(!empty($date_arr)){
                $param['sure_datetime'] = ['between', [trim($date_arr[0]), date('Y-m-d', strtotime ("+1 day", strtotime(trim($date_arr[1]))))]];
            }
        }
        $param['state'] = 6;
        $count = $this->model->where($param)->count();
        if($page > ceil($count/$limit)){
            $page = ceil($count/$limit);
        }
        $lst = $this->model->where($param)->order('sure_datetime desc,id desc')->page($page,$limit)->select();
        foreach ($lst as $item){
            $item['totall_price_tax'] = round(($item['freight'] + $item['totall_price'])*(100+$item['tax_rate'])/100);
            $item['opt_role_id'] = $role_id;
        }
        $pagobj =  $this->model->where($param)->field('sum(ROUND((freight+totall_price)*(100+tax_rate)/100)) as sum_total_price,sum(returned_money) as sum_returned_money')->find();
        $pagobj['returned_money_diff'] = round($pagobj['sum_total_price'] - $pagobj['sum_returned_money']);
        $pagobj['code'] = 0 ;
        $pagobj['msg'] = '';
        $pagobj['page'] = $page ;
        $pagobj['count'] = $count;
        $pagobj['data'] = $lst;
        return json($pagobj);
    }


    /**
     * 修改运费信息
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws PDOException
     */
    public function editFright()
    {
        $data = $this->trimParam();
        $info = $this->model->field('id,totall_price,tax_rate,returned_money')->where(['id'=>$data['id']])->find();
        $up_data = [
            'id'=>$data['id'],
            'freight'=>$data['freight'],
            'freight_type'=>$data['freight_type']
        ];
        try{
            $this->model->startTrans();

            /*if($info['returned_money']){
                if($info['returned_money']>= round(($info['totall_price']+$up_data['freight'])*(100+$info['tax_rate'])/100)){
                    $up_data['returned_money_state'] = 2;
                }else{
                    $up_data['returned_money_state'] = 1;
                }
            }*/

            $this->model->isUpdate(true)->save($up_data,['id'=>$data['id']]);
            $this->model->commit();
            json_return_code();
        }catch (\Exception $e){
            $this->model->rollback();
            json_return_code('','操作失败', '201');
        }
    }

    /**
     * 表格里修改运费或者税点
     * @return void
     * @throws PDOException
     */
    public function editFrightOrRate()
    {
        $data = $this->trimParam();
        if($data['tag_name'] == 'tax_amount'){
            $info = $this->model->field('id,freight,totall_price')->where(['id'=>$data['id']])->find()->toArray();
            $up_data['tax_rate'] = round($data['value']/($info['freight']+$info['totall_price'])*100,2);
        }else{
            $up_data[$data['tag_name']] = $data['value'];
        }
        try{
            $this->model->startTrans();
            $this->model->isUpdate(true)->save($up_data,['id'=>$data['id']]);
            $this->model->commit();
            $info = $this->getPriceInfo($data['id']);
            json_return_code($info);
        }catch (\Exception $e){
            $this->model->rollback();
            json_return_code('','操作失败', '201');
        }
    }
    /**
     * 生成采购单
     * @return void
     */
    public function createSales()
    {
        $data = $this->trimParam();
        $up_data = [
            'id'=>$data['id'],
            'freight'=>$data['freight'],
            'freight_type'=>$data['freight_type'],
            'tax_rate'=>$data['tax_rate']
        ];
        if($this->model->isUpdate(true)->save($up_data,['id'=>$data['id']]) !== false){
            json_return_code();
        }else{
            json_return_code('','操作失败', '201');
        }
    }
    /**
     * 收付款
     * @return void
     * @throws PDOException
     */
    public function payMoeny()
    {
        $data = $this->trimParam();
        $log_model = new AccountLog();
        $info = $this->model->field('id,returned_money_state,returned_money,totall_price,freight,tax_rate,bus_to_company_id,add_user_id')->where(['id'=>$data['id']])->find();
        $ins_data = [
            'order_id'=>$data['id'],
            'type'=>$data['type'],
            'company_type'=>$data['company_type'],
            'company_id'=>$info['bus_to_company_id'],
            'add_user_id'=>$info['add_user_id'],
            'account'=>$data['account'],
            'pay_type'=>$data['pay_type'],
            'pic_url'=>$data['pic_url'],
            'pay_datetime'=>$data['pay_datetime'],
            'common'=>$data['log_common'],
            'opt_user_id'=>$data['opt_user_id'],
            'opt_user_name'=>$data['opt_user_name'],
            'add_datetime'=>date('Y-m-d H:i:s')
        ];
        try{
            $this->model->startTrans();
            $log_model->insert($ins_data);
            $receive_money = round($info['returned_money'] + $ins_data['account']);
            $up_data = [
                'returned_money_state' => $data['returned_money_state'],
                'returned_money' => $receive_money,
                'returned_money_datetime' => date('Y-m-d H:i:s')
            ];
            /*if($receive_money >= round(($info['freight']+$info['totall_price'])*(100+$info['tax_rate'])/100)){
                $up_data['returned_money_state'] = 2;
            }else{
                $up_data['returned_money_state'] = 1;
            }*/
            $this->model->isUpdate(true)->save($up_data,['id'=>$data['id']]);
            $this->model->commit();
            addLog('付款给供应商');
            json_return_code();
        }catch (\Exception $e){
            $this->model->rollback();
            json_return_code('','操作失败', '201');
        }
    }

    /**
     * 修改打款记录
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws PDOException
     */
    public function editPayMoeny()
    {
        $data = $this->trimParam();
        $log_model = new AccountLog();
        $info = $this->model->field('id,returned_money_state,returned_money')->where(['id'=>$data['bus_inquiry_suppliers_id']])->find();
        $log_info = $log_model->where(['id'=>$data['id']])->find();

        $log_data = [
            'account'=>$data['account'],
            'pay_type'=>$data['pay_type'],
            'pic_url'=>$data['pic_url'],
            'pay_datetime'=>$data['pay_datetime'],
            'common'=>$data['common'],
            'update_datetime'=>date('Y-m-d H:i:s')
        ];
        try{
            $diff_money = $data['account'] - $log_info['account'];

            $this->model->startTrans();
            if($log_model->where(['id'=>$data['id']])->update($log_data) === false){
                throw new Exception('修改打款记录表失败');
            }
            $up_data = [
                'returned_money' => round($info['returned_money'] + $diff_money),
                'returned_money_datetime' =>date('Y-m-d H:i:s'),
                'returned_money_type' =>$data['pay_type'],
                'returned_money_state'=>$data['returned_money_state']
            ];
            if($this->model->isUpdate(true)->save($up_data,['id'=>$data['bus_inquiry_suppliers_id']]) === false) {
                throw new Exception('修改供应商报价记录表失败');
            }
            $this->model->commit();
            addLog('修改收款记录');
            json_return_code();
        }catch (\Exception $e){
            $this->model->rollback();
            addLog('修改打款记录失败！'.$e->getMessage());
            json_return_code('','操作失败', '201');
        }
    }

    /**
     * 删除打款记录
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws PDOException
     */
    public function delMoenyLog()
    {
        $data = $this->trimParam();
        $log_model = new AccountLog();
        $info = $this->model->field('id,returned_money_state,returned_money')->where(['id'=>$data['bus_inquiry_suppliers_id']])->find();
        $log_info = $log_model->where(['id'=>$data['id']])->find();

        try{
            $diff_money = -$log_info['account'];

            $this->model->startTrans();

            if($log_model::destroy($data['id']) === false){
                throw new Exception('修改打款记录表失败');
            }
            $up_data = [
                'returned_money' => round($info['returned_money'] + $diff_money),
                'returned_money_state'=>1
            ];
            if($this->model->isUpdate(true)->save($up_data,['id'=>$data['bus_inquiry_suppliers_id']]) === false) {
                throw new Exception('修改询价记录表失败');
            }
            $this->model->commit();
            addLog('修改收款记录');
            json_return_code();
        }catch (\Exception $e){
            $this->model->rollback();
            addLog('修改打款记录失败！'.$e->getMessage());
            json_return_code('','操作失败'.$e->getMessage(), '201');
        }
    }
    /**
     * 发货
     * @return void
     * @throws PDOException
     */
    public function sendGoods()
    {
        $data = $this->trimParam();
        $log_model = new SendGoodsLog();
        $ins_data = [
            'order_id'=>$data['id'],
            'company_type'=>$data['company_type'],
            'send_goods_state'=>$data['send_goods_state'],
            'pic_url'=>$data['pic_url'],
            'send_datetime'=>$data['send_datetime'],
            'common'=>$data['log_common'],
            'opt_user_id'=>$data['opt_user_id'],
            'opt_user_name'=>$data['opt_user_name'],
            'add_datetime'=>date('Y-m-d H:i:s')
        ];
        try{
            $this->model->startTrans();
            $log_model->insert($ins_data);
            $this->model->isUpdate(true)->save(['send_goods_state'=>$data['send_goods_state'],'send_goods_datetime'=>date('Y-m-d H:i:s')],['id'=>$data['id']]);
            $this->model->commit();
            addLog('供应商发货');
            json_return_code();
        }catch (\Exception $e){
            $this->model->rollback();
            json_return_code('','操作失败', '201');
        }
    }

    /**
     * 开票
     * @return void
     * @throws PDOException
     */
    public function invoice()
    {
        $data = $this->trimParam();
        $log_model = new InvoiceLog();
        $ins_data = [
            'order_id'=>$data['id'],
            'company_type'=>$data['company_type'],
            'pic_url'=>$data['pic_url'],
            'invoice_datetime'=>$data['invoice_datetime'],
            'common'=>$data['log_common'],
            'opt_user_id'=>$data['opt_user_id'],
            'opt_user_name'=>$data['opt_user_name'],
            'add_datetime'=>date('Y-m-d H:i:s')
        ];
        try{
            $this->model->startTrans();
            $log_model->insert($ins_data);
            $up_data = [
                'invoice_state' => 2,
                'invoice_datetime' => date('Y-m-d')
            ];
            $this->model->isUpdate(true)->save($up_data,['id'=>$data['id']]);
            $this->model->commit();
            addLog('供应商开票');
            json_return_code();
        }catch (\Exception $e){
            $this->model->rollback();
            json_return_code('','操作失败', '201');
        }
    }

    /**
     * 修改开票信息
     * @return void
     * @throws PDOException
     */
    public function editInvoice()
    {
        $data = $this->trimParam();
        $log_model = new InvoiceLog();
        $log_data = [
            'pic_url'=>$data['pic_url'],
            'state'=>$data['state'],
            'invoice_datetime'=>$data['invoice_datetime'],
            'common'=>$data['common'],
            'update_datetime'=>date('Y-m-d H:i:s')
        ];
        try{
            $this->model->startTrans();
            if($log_model->where(['id'=>$data['id']])->update($log_data) === false){
                throw new Exception('修改开票记录表失败');
            }
            if($data['state'] == 1){
                $up_data = [
                    'invoice_state' => 2,
                    'invoice_datetime' => date('Y-m-d')
                ];
            }else{
                $up_data = [
                    'invoice_state' => 0,
                    'invoice_datetime' => null
                ];
            }
            if($this->model->isUpdate(true)->save($up_data,['id'=>$data['bus_inquiry_suppliers_id']]) === false) {
                throw new Exception('修改询价记录表失败');
            }
            $this->model->commit();
            json_return_code();
        }catch (\Exception $e){
            $this->model->rollback();
            addLog('修改开票记录失败！'.$e->getMessage());
            json_return_code('','操作失败'.$e->getMessage(), '201');
        }
    }

    public function getDetailInfo(){
        $id = input('id');
        $info = $this->getPriceInfo($id);
        json_return_code($info);
    }

    /**
     * 获取详情信息
     * @param $id
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    private function getPriceInfo($id)
    {
        $info = $this->model->with('detailSales')->where(['id'=>$id])->find()->toArray();
        $info['tax_amount'] = round(($info['freight']+$info['totall_price'])*$info['tax_rate']/100);
        $info['totall_price_tax'] = round($info['freight']+$info['totall_price']+$info['tax_amount']);
        $add_arr = [
            [
                'id'=>-1,
                'eq_name'=>'配件总价',
                'price'=>'',
                'totall_price'=>$info['totall_price'],
                'make_sure_quilty'=>'',
                'state'=>'',
            ],
            [
                'id'=>-2,
                'eq_name'=>'运费+木架',
                'price'=>'',
                'totall_price'=>$info['freight'],
                'make_sure_quilty'=>'',
                'state'=>'',
            ],
            [
                'id'=>-3,
                'eq_name'=>'税金',
                'price'=>$info['tax_rate'],
                'totall_price'=>$info['tax_amount'],
                'make_sure_quilty'=>'',
                'state'=>'',
            ],
            [
                'id'=>-4,
                'eq_name'=>'总价',
                'price'=>'',
                'totall_price'=>$info['totall_price_tax'],
                'make_sure_quilty'=>'',
                'state'=>'',
            ]
        ];
        $info['detail_sales'] = array_merge($info['detail_sales'], $add_arr);
        return $info;
    }

    /**
     * 获取打款记录
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function getAccountLog(){
        $id = input('id');
        $page = input('page',1);
        $limit = input('limit',5);
        $log_model = new AccountLog();
        $param = [
            'order_id'=>$id,
            'company_type'=>2
        ];
        $count = $log_model->where($param)->count();
        if($page > ceil($count/$limit)){
            $page = ceil($count/$limit);
        }
        $lst = $log_model->where($param)->order('pay_datetime desc,id desc')->page($page,$limit)->select();
        return json_tab_msg($count,$page,$lst);
    }

    /**
     * 获取发货记录
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function getSendGoodsLog(){
        $id = input('id');
        $page = input('page',1);
        $limit = input('limit',5);
        $log_model = new SendGoodsLog();
        $param = [
            'order_id'=>$id,
            'company_type'=>2
        ];
        $count = $log_model->where($param)->count();
        if($page > ceil($count/$limit)){
            $page = ceil($count/$limit);
        }
        $lst = $log_model->where($param)->order('send_datetime desc,id desc')->page($page,$limit)->select();
        return json_tab_msg($count,$page,$lst);
    }

    /**
     * 获取开票记录
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function getInvoiceLog()
    {
        $id = input('id');
        $page = input('page',1);
        $limit = input('limit',5);
        $log_model = new InvoiceLog();
        $param = [
            'order_id'=>$id,
            'company_type'=>2
        ];
        $count = $log_model->where($param)->count();
        if($page > ceil($count/$limit)){
            $page = ceil($count/$limit);
        }
        $lst = $log_model->where($param)->order('invoice_datetime desc,id desc')->page($page,$limit)->select();
        return json_tab_msg($count,$page,$lst);
    }


    /**
     * 退件
     * @return void
     * @throws PDOException
     */
    public function returnsEq()
    {
        $data = $this->trimParam();
        $this->model->startTrans();
        try {
            // 退采购
            $supplierDetailModel = new BusInquiryDetailSupplier();
            $info = $supplierDetailModel->field('id,bus_inquiry_suppliers_id,bus_inquiry_detail_id,bus_inquiry_id,totall_price')->where(['id'=>$data['id']])->find();
            $suppliersInfo = $this->model->field('id,totall_price,freight,tax_rate,returned_money')->where(['id'=>$info['bus_inquiry_suppliers_id']])->find();

            $supplier_detail_data = [
                'state'=>4,
                'returns_common'=>$data['returns_common'],
                'returns_datetime'=>date('Y-m-d H:i:s'),
            ];
            $supplier_data = [
                'totall_price'=>$suppliersInfo['totall_price'] - $info['totall_price'],
                'have_returns'=>1,
            ];
            /*if(!$suppliersInfo['returned_money']){
                $supplier_data['returned_money_state'] = 0;
            }elseif($suppliersInfo['returned_money']>= round(($suppliersInfo['freight']+$supplier_data['totall_price'])*(100+$suppliersInfo['tax_rate'])/100)){
                $supplier_data['returned_money_state'] = 2;
            }else{
                $supplier_data['returned_money_state'] = 1;
            }*/
            $supplierDetailModel->isUpdate(true)->save($supplier_detail_data,['id'=>$data['id']]);
            $this->model->isUpdate(true)->save($supplier_data,['id'=>$info['bus_inquiry_suppliers_id']]);

            //退保险公司
            if($data['returns_type'] == 2){
                $inquiryModel = new BusInquiry();
                $inquiryDetailModel = new BusInquiryDetail();
                $detailInfo = $inquiryDetailModel->field('id,totall_price')->where(['id'=>$info['bus_inquiry_detail_id']])->find();
                $inquiryInfo = $inquiryModel->field('id,totall_price,freight,tax_rate,returned_money')->where(['id'=>$info['bus_inquiry_id']])->find();

                $detail_data = [
                    'state'=>4,
                    'returns_common'=>$data['returns_common'],
                    'returns_datetime'=>date('Y-m-d H:i:s'),
                ];
                $inquiry_data = [
                    'totall_price'=>$inquiryInfo['totall_price'] - $detailInfo['totall_price'],
                ];
                /*if(!$inquiryInfo['returned_money']){
                    $inquiry_data['returned_money_state'] = 0;
                }elseif($inquiryInfo['returned_money']>= round(($inquiryInfo['freight']+$inquiry_data['totall_price'])*(100+$inquiryInfo['tax_rate'])/100)){
                    $inquiry_data['returned_money_state'] = 2;
                }else{
                    $inquiry_data['returned_money_state'] = 1;
                }*/

                $inquiryDetailModel->isUpdate(true)->save($detail_data,['id'=>$info['bus_inquiry_detail_id']]);
                $inquiryModel->isUpdate(true)->save($inquiry_data,['id'=>$info['bus_inquiry_id']]);
            }
            $this->model->commit();
            addLog('退件');
            json_return_code();
        }catch (\Exception $e){
            $this->model->rollback();
            json_return_code('','操作失败'.$e->getMessage(), '201');
        }
    }

    /**
     * 补充凭证
     * @return void
     */
    public function editPic()
    {
        $id = input('id');
        $type = input('up_type');
        $pic_url = input('pic_url');
        if($type === 'invoice'){
            $model = new InvoiceLog();
        }elseif ($type === 'account'){
            $model = new AccountLog();
        }else{
            json_return_code('','请确认信息', '201');
        }
        if($model->where(['id'=>$id])->update(['pic_url'=>$pic_url]) !== false){
            addLog('上传凭证');
            json_return_code();
        }else{
            json_return_code('','操作失败', '201');
        }
    }
}